/**
 * Copyright (c) 2014 by it's authors. 
 * All rights reserved. See COPYING, AUTHORS.
 * 
 * This file is part of DanceMania project; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License, Version 3.
 * 
 * DanceMania is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License,
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */
package com.m2dl.niptus.pathtrack.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.m2dl.niptus.pathtrack.utils.Constants;

public class DBAdapter {
	private final static String TAG = Constants.TAG + ".DBAdapter";

	public static final String DATABASE_NAME = "PathTrack.db";
	private static final int DATABASE_VERSION = 1;

	private static final String OBJECT_TABLE = "objects";
	private static final String[] OBJECT_COLUMNS = { "id", "x", "y" };

	private static final String OBJECT_TABLE_CREATE = "create table "
			+ OBJECT_TABLE + " (" + OBJECT_COLUMNS[0]
			+ " integer primary key autoincrement, " 
			+ OBJECT_COLUMNS[1]	+ " real not null," 
			+ OBJECT_COLUMNS[2]	+ " real not null);";

	private final Context context;

	private DatabaseHelper DBHelper;
	private SQLiteDatabase db = null;

	public DBAdapter(Context ctx) {
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
		open();
	}

	public DBAdapter open() throws SQLException {
		if (db == null)
			db = DBHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
		DBHelper.close();
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				db.execSQL(OBJECT_TABLE_CREATE);
			} catch (SQLException e) {
				Log.e(TAG, e.getMessage());
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + OBJECT_TABLE);
			onCreate(db);
		}
	}

	// Update object
	public void updateObject(int id, String name, String quantity) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(OBJECT_COLUMNS[1], name);
		initialValues.put(OBJECT_COLUMNS[2], quantity);

		db.update(OBJECT_TABLE, initialValues, OBJECT_COLUMNS[0] + "=" + id,
				null);
	}

	// Insert with update check
	public Location insertObject(double x, double y) {
		Location r = new Location(x, y);

		ContentValues initialValues = new ContentValues();
		initialValues.put(OBJECT_COLUMNS[1], x);
		initialValues.put(OBJECT_COLUMNS[2], y);

		int id = (int) db.insertOrThrow(OBJECT_TABLE, null, initialValues);
		r.setId(id);

		return r;
	}

	public Location getObject(int id) {
		Location r = new Location();

		Cursor c = db.query(OBJECT_TABLE, null, OBJECT_COLUMNS[0] + "=" + id,
				null, null, null, null);

		if (c.getCount() != 0) {
			c.moveToFirst();
			r.setId(c.getInt(c.getColumnIndex(OBJECT_COLUMNS[0])));
			r.setX(c.getDouble(c.getColumnIndex(OBJECT_COLUMNS[1])));
			r.setY(c.getDouble(c.getColumnIndex(OBJECT_COLUMNS[2])));

			return r;
		} else {
			return null;
		}
	}

	public List<Location> getAllObjects() {
		List<Location> r = new ArrayList<Location>();

		Cursor c = db.query(OBJECT_TABLE, null, null, null, null, null, null);

		if (c.getCount() > 0) {
			c.moveToFirst();
			do {
				r.add(new Location(c.getInt(c.getColumnIndex(OBJECT_COLUMNS[0])),
						c.getDouble(c.getColumnIndex(OBJECT_COLUMNS[1])), 
						c.getDouble(c.getColumnIndex(OBJECT_COLUMNS[2]))));
			} while (c.moveToNext());
		}
		c.moveToFirst();

		return r;
	}

	public Location insertObject(Location item) {
		return insertObject(item.getX(), item.getY());
	}

	public int deleteObject(int id) {
		return db.delete(OBJECT_TABLE, OBJECT_COLUMNS[0] + "=" + id, null);
	}

	public void cleanDB() {
		Cursor c = db.query(OBJECT_TABLE, null, null, null, null, null, null);

		if (c.getCount() > 0) {
			c.moveToFirst();
			do {
				int id = c.getInt(c.getColumnIndex(OBJECT_COLUMNS[0]));
				deleteObject(id);
			} while (c.moveToNext());
		}
		c.moveToFirst();

		ContentValues initialValues = new ContentValues();
		initialValues.put("seq", 0);

		db.update("sqlite_sequence", initialValues, "name=\'objects\'", null);
	}
}